package Dao;

import org.apache.commons.dbutils.*;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.omg.CORBA.Object;
import utils.JdbcUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public abstract class BaseDao {
    //使用 sql server
    private QueryRunner queryRunner = new QueryRunner();


    /*
    * update()方法用来执行，insert/update/delete语句
    *
    * */
    public int update(String sql, java.lang.Object...args) throws Exception {
        Connection conn = getConnection();
        try {
          return  queryRunner.update(conn,sql,args);
        }catch (SQLException e){
            e.printStackTrace();
        }
        conn.close();
        return -1;

    }

    /*查询返回一个javaBean的sql语句
    * type 返回的对象类型
    * sql 执行的sql语句
    * args sql对应的参数值
    * <T> 返回类型的泛型
    * */
    public <T>T queryForOne(Class<T> type, String sql, java.lang.Object...args) throws Exception {
        Connection con = getConnection();
        try{
            return  queryRunner.query(con,sql,new BeanHandler<T>(type),args);
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            con.close();
        }
        return null;
    }

    public <T> List<T> queryForList(Class<T> type, String sql, java.lang.Object...args) throws Exception {
        Connection con = getConnection();
        try{
            return  queryRunner.query(con,sql,new BeanListHandler<>(type),args);
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            con.close();
        }
        return null;
    }


    /*
    * 执行返回一行一列的参数值
    * sql 执行的sql语句
    * args sql对应的参数值
    *
    * */

    public java.lang.Object queryForSingleValue(String sql, java.lang.Object...args) throws Exception {
        Connection con = getConnection();
        try {
            return  queryRunner.query(con, sql, new ScalarHandler(),args);
        }catch (SQLException e){
            e.printStackTrace();
        }
        con.close();
        return null;
    }


    public static Connection getConnection() throws Exception {
        return JdbcUtils.getConnection();
    }
}
